const fs = require('fs')

module.exports = class InjectionVersionNumberPlugin {
  constructor(props) {
    this.props = props
  }

  apply(compiler) {
    const { name, versionPath, htmlPath } = this.props
    compiler.hooks.done.tap('InjectionVersionNumberPlugin', () => {
      const version = Date.now().toString()

      // 版本号写入服务端文件
      fs.writeFile(
        versionPath,
        JSON.stringify({ version, content: '更新新版本, 修复bug问题等', title: '发现新版本' }),
        'utf8',
        () => {}
      )

      // 版本号写入用户本地缓存
      fs.readFile(htmlPath, 'utf8', (error, data) => {
        if (error) throw error

        const [bodyBefore, bodyAfter] = data.split('<body>')
        const injectScript = `
          <script>
            !localStorage.${name} && localStorage.setItem('${name}', ${version});
          </script>
        `
        fs.writeFile(htmlPath, [bodyBefore, injectScript, bodyAfter].join(''), 'utf8', () => {})
      })
    })
  }
}
